import { defineStore } from "pinia";
import { useStorage } from "@vueuse/core";
import type {
  RouteLocationNormalized,
  LocationQuery,
  RouteParams,
} from "vue-router";

export interface TagItem {
  title: string;
  path: string;
  fullPath: string; // 完整路径（包含参数）
  query?: LocationQuery; // 查询参数
  params?: RouteParams; // 路由参数
  affix?: boolean; // 是否固定
  icon?: string;
  time?: number; // 访问时间戳
}

export const useTagsStore = defineStore("tags", () => {
  // 使用 localStorage 持久化存储标签
  const tags = useStorage<TagItem[]>("tags", []);

  // 添加标签
  function addTag(route: RouteLocationNormalized) {
    const { name, path, fullPath, meta, query, params } = route;

    // 不记录没有名称的路由和设置了 noTag 的路由
    if (!name || meta?.noTag || !meta?.title) {
      return;
    }

    const tag: TagItem = {
      title: meta?.title as string,
      path,
      fullPath,
      query: { ...query },
      params: { ...params },
      icon: typeof meta?.icon === "string" ? meta.icon : undefined,
      affix: meta?.affix as boolean,
      time: Date.now(),
    };

    const index = tags.value.findIndex((item) => item.path === path);

    if (index > -1) {
      // 更新已存在的标签
      Object.assign(tags.value[index], {
        title: tag.title,
        fullPath,
        query,
        params,
        time: tag.time,
      });
    } else {
      // 添加新标签
      tags.value.push(tag);
    }
  }

  // 移除标签
  function removeTag(fullPath: string) {
    const index = tags.value.findIndex((item) => item.fullPath === fullPath);
    if (index !== -1 && !tags.value[index].affix) {
      tags.value.splice(index, 1);
    }
  }

  // 获取相邻的标签
  function getNextTag(fullPath: string) {
    const index = tags.value.findIndex((item) => item.fullPath === fullPath);
    if (index === -1) return undefined;

    // 优先返回右侧标签，没有则返回左侧标签
    return tags.value[index + 1] || tags.value[index - 1];
  }

  // 关闭其他标签
  function closeOtherTags(fullPath: string) {
    tags.value = tags.value.filter(
      (tag) => tag.affix || tag.fullPath === fullPath
    );
  }

  // 关闭左侧标签
  function closeLeftTags(fullPath: string) {
    const index = tags.value.findIndex((item) => item.fullPath === fullPath);
    if (index > 0) {
      const affixTags = tags.value.filter((tag) => tag.affix);
      const remainTags = tags.value.slice(index);
      tags.value = [...affixTags, ...remainTags];
    }
  }

  // 关闭右侧标签
  function closeRightTags(fullPath: string) {
    const index = tags.value.findIndex((item) => item.fullPath === fullPath);
    if (index > -1) {
      tags.value = tags.value.slice(0, index + 1);
    }
  }

  // 关闭所有标签
  function closeAllTags() {
    tags.value = tags.value.filter((tag) => tag.affix);
  }

  // 更新标签信息
  function updateTag(fullPath: string, tag: Partial<TagItem>) {
    const item = tags.value.find((item) => item.fullPath === fullPath);
    if (item) {
      Object.assign(item, tag);
    }
  }

  function $reset() {
    tags.value = [];
  }

  return {
    tags,
    addTag,
    removeTag,
    getNextTag,
    closeOtherTags,
    closeLeftTags,
    closeRightTags,
    closeAllTags,
    updateTag,
    $reset,
  };
});
